import * as shlib from 'shlib/browser'

import { ShTerm } from './index'
import { ShElement } from './ShElement'
import { ShSpanElement } from './ShSpanElement'


export class ShRowElement extends ShElement {

    public static create(): ShRowElement {
        return shlib.createElement('shterm-row') as ShRowElement
    }

    constructor() {
        super()
    }

    public countColumns(): number {
        let cols = 0
        for (let i = 0; i < this.children.length; i++) {
            const $span = this.children[i]! as ShSpanElement
            cols += $span.countColumns()
        }

        return cols
    }

    /**
     * 将 $span 添加到本行末尾。如果 $span 的文本属性与本行最后一个 span 的显示属性相同，则
     * 将 $span 的内容合并到最后一个 span 中，不添加新的 span。
     */
    public appendSpan($span: ShSpanElement) {
        if (this.children.length === 0) {
            this.appendChild($span)
            return
        }

        const $lastSpan = this.children[this.children.length - 1] as ShSpanElement
        if ($lastSpan.compareTextAttribute($span)) {
            $lastSpan.setText($lastSpan.innerText + $span.innerText)
            $span.remove()
        }
        else
            this.appendChild($span)
    }

    public updateLayout($term?: ShTerm | null) {
        $term = $term || this.$term()
        shlib.assertNotNull($term)

        for (const $span of this.children) {
            ;($span as ShSpanElement).updateLayout($term)
        }
    }

    public breakAt(maxCol: number): ShSpanElement | null {
        for (let i = 0; i < this.children.length; i++) {
            const $span = this.children[i]! as ShSpanElement
            const ncols = $span.countColumns()
            if (maxCol < ncols)
                return $span.breakAt(maxCol)

            maxCol -= ncols
        }

        return null
    }

    public insertAt(col: number, $span: ShSpanElement) {
        const $left = this.breakAt(col)
        if ($left) {
            $left.insertAdjacentElement('afterend', $span)
        } else {
            this.appendChild($span)
        }
    }

    public replaceAt(col: number, $span: ShSpanElement) {

    }
}

customElements.define('shterm-row', ShRowElement)